import urllib.parse
import hashlib
from collections import defaultdict
import uuid
from datetime import datetime

def get_sign(app_key, app_secret, uuid, timestamp, url, url_params=None):
    try:
        # 初始化参数映射
        params = defaultdict(str)

        # 解析URL中的查询参数
        if '?' in url:
            query_params = url.split('?')[1]
            for param in query_params.split('&'):
                key_value = param.split('=')
                key = urllib.parse.unquote(key_value[0])
                if key == 'sign':
                    continue  # 跳过 "sign" 参数
                value = urllib.parse.unquote(key_value[1]) if len(key_value) > 1 else ''
                params[key] = value

        # 添加额外的URL参数
        if url_params:
            for key, value in url_params.items():
                params[key] = str(value) if value is not None else ''

        # 对参数键进行排序
        key_sort = sorted(params.keys())

        print(key_sort)

        # 构建签名盐（signSalt）
        sign_salt = ''
        for key in key_sort:
            if key == 'sign':
                continue  # 跳过 "sign" 参数
            sign_salt += key + params[key]
        
        print("sign_salt : ", sign_salt)

        # 生成最终的签名字符串
        return get_sha256(app_key + timestamp + uuid + app_secret + sign_salt)
    except Exception as e:
        raise Exception("生成签名异常，检查参数URL是否正确!", e)

def get_sha256(origin):
    try:
        sha256 = hashlib.sha256()
        sha256.update(origin.encode('utf-8'))
        return sha256.hexdigest()
    except Exception as e:
        raise Exception("找不到对应的加密算法.", e)
    
def get_timestamp():
    # 获取当前时间
    now = datetime.now()

    # 获取当前时间的毫秒级时间戳
    timestamp_ms = now.timestamp()

    print("当前时间的毫秒级时间戳：", timestamp_ms)
    return timestamp_ms

# 示例使用
if __name__ == "__main__":
    capNo = "K1801064507523592193"
    app_key = "K1866371139455021057"
    app_secret = "AEifXnSpBwp9nygX"
    uuid_str = str(uuid.uuid1())
    timestamp = get_timestamp()
    url = f"https://open.ctedu.com.cn/open/isvc/open/isvc?capNo={capNo}&appKey={app_key}&signVersion=1.0.0&uuid={uuid_str}&timestamp={timestamp}&sign=xx"
    # url_params = {"param3": "value3", "param4": "value4"}

    sign = get_sign(app_key, app_secret, uuid_str, timestamp, url, None)
    print(f"生成的签名: {sign}")